import { Is } from "../constants/enum";
import { index, Prop, modelOptions, DocumentType, getModelForClass } from "@typegoose/typegoose";
import { ReturnModelType } from "@typegoose/typegoose/lib/types";
import BaseEntity from "../common/base.entity";
import { md5, uuid } from "../util/utilities";
import { pinyin } from 'pinyin-pro';

@modelOptions({
  schemaOptions: {
    collection: 'users',
  }
})
@index({ uid: 1 })
@index({ name: 1 })
export class UserEntity extends BaseEntity {
  @Prop({ required: true, unique: true, default: uuid() })
  public uid!: string;

  @Prop({
    default: function (this: DocumentType<UserEntity>) {
      return pinyin(this.nickname, { toneType: 'none' });
    }
  })
  public name?: string;

  @Prop({ required: true, unique: true, trim: true, maxlength: 16 })
  public nickname!: string;

  @Prop({ enum: Is, default: Is.yes })
  public male!: Is;

  @Prop()
  public mobile?: string;

  @Prop()
  public email?: string;

  @Prop({ required: true, minlength: 6, maxlength: 16, transform: (value: string) => { return md5(value); } })
  public password!: string;

  @Prop()
  public avatar?: string;

  @Prop()
  public birthday?: number;

  @Prop()
  public city?: string;

  @Prop({ trim: true })
  public description?: string;

  @Prop({ enum: Is, default: Is.yes })
  public enabled?: Is;

  @Prop()
  public first_scan_time?: number; // 秒时间戳

  @Prop()
  public last_scan_time?: number;

  @Prop({ trim: true })
  public token?: string;

  // static method
  public static async getUserById(this: ReturnModelType<typeof UserEntity>, uid: string) {
    return await this.findOne({ uid });
  }

  public static async enableUser(this: ReturnModelType<typeof UserEntity>, uid: string, value: Is): Promise<void> {
    await this.updateOne({ uid }, { $set: { enabled: value }});
  }
}

export const UserModel: ReturnModelType<typeof UserEntity> = getModelForClass(UserEntity);

export const USER_BASE_PROJECTION = {
  _id: 0,
  nickname: 1,
  description: 1,
  city: 1,
  avatar: 1
};
export const USER_COMMON_PROPERTIES = [
  'name', 'nickname', 'mobile', 'email', 'gender',
  'avatar', 'birthday', 'description', 'city'
];




